package com.lej.club.app

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.os.Build
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.launcher.ARouter
import com.lej.app_main.launcher.LauncherActivity
import com.lej.club.BuildConfig
import com.lej.club.R
import com.lej.core.base.AppManager
import com.lej.core.base.BaseApplication
import com.lej.core.common.PCacheInfo
import com.lej.core.common.hasPermission
import com.lej.core.crash.CaocConfig
import com.lej.core.daq.DAQEvent
import com.lej.core.utils.extention.logI
import com.lej.core.utils.isMainProcess
import com.lej.dataservice.club.http.baseApiService
import com.lej.dataservice.club.http.checkData
import com.lej.home.HHomeActivity
import com.lej.share.core.CheckShareCodeLifeCycleCallback
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.tencent.bugly.crashreport.CrashReport
import tv.danmaku.ijk.media.player.IjkMediaPlayer

class AppApplication : BaseApplication() {
    override val isDebug = BuildConfig.DEBUG

    override fun onCreate() {
        super.onCreate()
        initRouter()
        //初始化全局异常崩溃
        initCrash()
        if (PCacheInfo.uuid.isEmpty()) PCacheInfo.uuid = sessionId
        initDAQ()
        initCrashReport()
        initVideoPlayer()
        AppManager.setHomeActivity(HHomeActivity::class.java)
        moduleAppInit()
    }

    /**
     * 适配android 9 webView多进程问题
     */
    private fun initWebView() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
            val processName = getProcessStr()
            processName?.let {
                if(!packageName.equals(processName)){
                    WebView.setDataDirectorySuffix(processName)
                }
            }
        }
    }

    private fun getProcessStr():String?{
        val manager: ActivityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for(processInfo: ActivityManager.RunningAppProcessInfo in manager.runningAppProcesses){
            if(processInfo.pid == android.os.Process.myPid()){
                return processInfo.processName
            }
        }
        return null
    }

    /** module初始化*/
    private fun moduleAppInit() {
        for (baseAppInit in initList) {
            baseAppInit.onInit(this)
            baseAppInit.privacyInit(this, hasPermission())
        }
    }

    private fun initCheckShareCode() {
        registerActivityLifecycleCallbacks(object : CheckShareCodeLifeCycleCallback() {
            val flag = '€'
            val codeRegex = "$flag[a-zA-Z0-9]{1,15}$flag".toRegex()
            override fun onActivityResumed(activity: Activity) {
                if (PCacheInfo.token.isEmpty()) return
                super.onActivityResumed(activity)
            }

            override fun onActivityPaused(activity: Activity) {
                if (PCacheInfo.token.isEmpty()) return
                super.onActivityPaused(activity)
            }

            override fun checkTimeAndText(time: Long, text: String, activity: Activity) {
                ///如果有时间，检查剪贴板时间是否判断过
                if (time > 0L && time > PCacheInfo.lastCheckClipboardTime)
                    codeRegex.find(text)?.value?.trim(flag)?.let {
                        if (time <= 0L && PCacheInfo.lastCheckClipboardCode == it) return

                        (activity as AppCompatActivity).lifecycleScope.launchWhenResumed {
                            kotlin.runCatching {
                                DAQEvent.share_copy_peng_code.mobEvent("start")
                                baseApiService.exchangecodeinfo(it).checkData()
                                DAQEvent.share_copy_peng_code.mobEvent("success")
                                PCacheInfo.lastCheckClipboardCode = it
                                PCacheInfo.lastCheckClipboardTime = time
                            }
                        }

                    }
            }
        })
    }

    private fun initVideoPlayer() {
        //EXOPlayer 内核，支持格式更多
//        PlayerFactory.setPlayManager(Exo2PlayerManager::class.java)
        //切换绘制模式
        //        GSYVideoType.setRenderType(GSYVideoType.SUFRACE);
        //        GSYVideoType.setRenderType(GSYVideoType.GLSURFACE);
//        GSYVideoType.setRenderType(GSYVideoType.TEXTURE)
        //ijk关闭log
        IjkPlayerManager.setLogLevel(IjkMediaPlayer.IJK_LOG_SILENT)
    }

    private fun initCrash() {
        CaocConfig.Builder.create()
            .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //背景模式,开启沉浸式
            .enabled(true) //是否启动全局异常捕获
            .showErrorDetails(true) //是否显示错误详细信息
            .showRestartButton(true) //是否显示重启按钮
            .trackActivities(true) //是否跟踪Activity
            .minTimeBetweenCrashesMs(2000) //崩溃的间隔时间(毫秒)
            .errorDrawable(R.mipmap.ic_launcher) //错误图标
            .restartActivity(LauncherActivity::class.java) //重新启动后的activity
            .apply()
    }

    private fun initRouter() {
        if (isDebug) { // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog() // 打印日志
            ARouter.openDebug() // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this) // 尽可能早，推荐在Application中初始化
    }

    private fun initCrashReport() {
        if (hasPermission() && isMainProcess()) {
            "-1--CrashReport init".logI("sss")
            CrashReport.initCrashReport(this, BuildConfig.BUGLY_APP_ID, isDebug)
            CrashReport.setIsDevelopmentDevice(this, isDebug)
            CrashReport.putUserData(this, "sid", PCacheInfo.uuid)
        }
    }

    private fun initDAQ() {
        if (hasPermission() && isMainProcess()) {
            DAQEvent.eventDev()//初始化的时候上报设备信息
        }
    }

    /**获取权限后回调*/
    override fun privacyInit() {
        initWebView()
        initCrashReport()
        initDAQ()
        for (baseAppInit in initList) {
            baseAppInit.privacyInit(this, hasPermission())
        }
    }
}